<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $code = 100000;
    protected $msg = '保存成功';
    protected $data = [];

    /**
     * 自定义ajax返回格式，并生成response
     *
     * @param $code
     * @param $msg
     * @param array $data
     * @param int $status
     * @param array $headers
     * @return Response
     */
    public function ajaxResult($code, $msg, $data = '', $status = 200, Array $headers = ['content-type' => 'application/json;charset=UTF-8'])
    {
//        $token = $this->tokenGenerator();
        return Response::create(['code' => $code, 'msg' => $msg, 'data' => $data], $status, $headers);
    }

    /**
     * 加密方式
     * @param $password
     * @return string
     */
    protected function encrypt($password)
    {
        return md5($password);
    }

    /**
     * 令牌生成器
     * @return string
     */
    protected function tokenGenerator()
    {
        $time = time();
        $timeStr = strval($time);
        $timeStr1 = substr($timeStr, 0, 3);
        $timeStr2 = substr($timeStr, 3, 3);
        $timeStr3 = substr($timeStr, 6, 4);
        $timeMD5 = md5($time);
        $token = $timeStr1 . substr_replace($timeMD5, $timeStr2, 16, 0) . $timeStr3;
        request()->session()->put(config('yucheng.token'), $token);
        return $token;
    }

    /**
     * 列表转树型
     * @param $arr
     * @param int $pid
     * @return array
     */
    protected function listToTree($arr,$pid=0) {
        $ret = array();
        foreach($arr as $k => $v) {
            if($v->pid == $pid) {
                $tmp = $arr[$k];unset($arr[$k]);
                $tmp->children = $this->listToTree($arr,$v->id);
                $ret[] = $tmp;
            }
        }
        return $ret;
    }

    /**
     * @param $data
     * @param $count
     * @return array
     */
    public function tableFormat($data,$count){
        return ["data" => $data, "count" => $count,];
    }

    /**
     * @param $method
     * @return bool|string
     */
    protected function getMethodName($method){
        $pos = strripos($method,':');
        return substr($method,$pos+1);
    }
}
